import style from '../pages/spiders/Spiders.module.scss';
import {
  CheckCircleFilled,
  ClockCircleFilled,
  CloseCircleFilled,
  LoadingOutlined,
  MinusCircleFilled,
  SyncOutlined,
} from '@ant-design/icons';
import React from 'react';
import {Tag} from 'antd';

export const processSpider = (spider) => {
  const result = Object.assign({}, spider);
  if (!spider) return undefined;
  result.formattedOutput = [];
  result.originalStartedAt = spider.started_at;
  result.originalFinishedAt = spider.finished_at;
  result.created_at =
    spider.created_at ? new Date(spider.created_at).toLocaleString() : '未知';
  result.finished_at =
    spider.finished_at ? new Date(spider.finished_at).toLocaleString() : '未知';
  result.started_at =
    spider.started_at ? new Date(spider.started_at).toLocaleString() : '未知';
  let curLine = null;
  spider.stdout
      ?.split('\n')
      .filter((l) => l)
      .forEach((line) => {
        if (line[20] === '[' && line[4] === '-' && line[7] === '-') {
        // 起始行
          if (curLine) {
            result.formattedOutput.push(curLine);
          }
          curLine = {};
          curLine.time = line.slice(0, 19);
          curLine.origin = line.slice(21, line.indexOf(']'));
          curLine.level = line.slice(
              line.indexOf(']') + 2,
              line.indexOf(':', 21),
          );
          curLine.content = line.slice(
              line.indexOf(':', 21) + 2,
          ).trim();
          curLine.following = [];
          if (curLine.content.match(/^customJson/)) {
            curLine.parsedContent = JSON.parse(curLine.content.slice(10));
            // console.log(curLine.parsedContent)
            const {type, value} = curLine.parsedContent;
            switch (type) {
              case 'closed':
                result.closeReason = value;
                break;
              case 'totalCount':
                result.totalCount = value;
                break;
              case 'progress':
                result.progress = value;
                break;
              default:
            }
          }
        } else {
          if (curLine) {
            curLine.following.push(line);
          } else {
            result.formattedOutput.push({
              unrecognized: line,
            });
          }
        }
      });
  if (curLine) {
    result.formattedOutput.push(curLine);
  }
  let curCount;
  if (spider.type==='comment') {
    curCount=result.progress || 0;
  } else if (spider.type==='jd') {
    curCount=spider.jd_books_count;
  } else {
    curCount=spider.dd_books_count;
  }
  const totCount = spider.max_count ?
    Math.min(result.totalCount, spider.max_count) : result.totalCount;
  result.percent = ((curCount / totCount * 100) || 0
  ).toFixed(2);
  return result;
};

export const getTimeDifference = (a, b) => {
  const d = Math.round(((new Date(b)) - (new Date(a))) / 1000);
  return `${Math.floor(d / 60)}:${d % 60}`;
};

export const statusIcon = {
  finished: <Tag icon={<CheckCircleFilled/>} className={style.statusIcon}
    color="success">成功结束
  </Tag>,
  failed: <Tag icon={<CloseCircleFilled/>} className={style.statusIcon}
    color="error">失败
  </Tag>,
  queuing: <Tag icon={<ClockCircleFilled/>} className={style.statusIcon}
    color={'purple'}>排队中
  </Tag>,
  running: <Tag icon={<SyncOutlined spin/>} className={style.statusIcon}
    color={'processing'}>运行中
  </Tag>,
  cancelling: <Tag icon={<LoadingOutlined/>} className={style.statusIcon}
    color={'warning'}>取消中
  </Tag>,
  cancelled: <Tag icon={<MinusCircleFilled/>} className={style.statusIcon}
    color="warning">已取消
  </Tag>,
};

export const getFullCoverURL = (url) => {
  if (url.match(/^http/)) {
    return url;
  }
  return '//img10.360buyimg.com/n2/s240x240_' + url;
};

export const getSortMethodText = {
  'idx': '按最高排名排序',
  // 'max_p': '按最高价格排序',
  // 'min_p': '按最低价格排序',
  'avg_p': '按均价排序',
  'mention': '按出现次数排序',
  'publish_date': '按出版时间排序',
  'comment_count': '按评论数排序',
  'average_score': '按平均得分排序',
};

export const getDatabaseSearchMethodText = {
  'avg_p': '按均价排序',
  'mention': '按出现次数排序',
  'publish_date': '按出版时间排序',
  'comment_count': '按评论数排序',
  'average_score': '按平均得分排序',
};

export const getDatabaseSearchItemText={
  'all': '任何位置',
  'name': '名称',
  'author': '作者/译者',
  'digest': '摘要',
  'publisher': '出版社',
};

export const getPercentile = (data, cur) => {
  let leftSum=0; let rightSum=0;
  for (const datum of data) {
    if (Number(cur)>datum.key) {
      leftSum+=datum.value;
    } else {
      rightSum+=datum.value;
    }
  }
  return ((leftSum/(leftSum+rightSum))*100).toFixed(0)+'%';
};
